package com.hualian.user.controller;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.hualian.system.common.Constants;
import com.hualian.user.entiy.User;
import com.hualian.user.entiy.UserParam;
import com.hualian.user.service.UserService;
import com.hualian.util.file.FileUtil;
import com.hualian.util.http.MD5Util;
import com.hualian.util.http.RequestUtil;

@RestController
@RequestMapping("/user")
public class UserController {
	
	
	@Autowired
	private UserService userService;
	
	
	/**
	 * 跳转到登录页面
	 * @return
	 */
	@RequestMapping("/tologin")
	public ModelAndView toLogin() {
		return new ModelAndView("/user/login");
	}

	/**
	 * 跳转到注册页面
	 * @param session
	 * @return
	 */
	@RequestMapping("/toregist")
	public ModelAndView toRegist(HttpSession session) {
		return new ModelAndView("/user/regist");
	}
	
	/**
	 * 跳转到用户中心
	 * @param session
	 * @return
	 */
	@RequestMapping("/tousercenter")
	public ModelAndView toUserCenter(HttpSession session) {
		ModelAndView mav = showUserCenter(session);
		mav.setViewName("user/usercenter");
		return mav;
	}
	
	
	/**
	 * 跳转到用户中心编辑界面
	 * @param session
	 * @return
	 */
	@RequestMapping("/tousercenteredit")
	public ModelAndView toUserCenterEdit(HttpSession session) {
		ModelAndView mav = showUserCenter(session);
		mav.setViewName("user/usercenteredit");
		return mav;
	}
	
	
	/**
	 * 跳转到修改密码界面
	 * @param session
	 * @return
	 */
	@RequestMapping("/tomodifypassword")
	public ModelAndView toModifyPassword() {
		return new ModelAndView("modifypassword");
	}
	
	
	/**
	 * 跳转到修改支付密码界面
	 * @param session
	 * @return
	 */
	@RequestMapping("/toModifyPayPassword")
	public ModelAndView toModifyPayPassword() {
		return new ModelAndView("modifyPayPassword");
	}
	
	
	
	/**
	 * 跳转到银行卡管理界面
	 * @param session
	 * @return
	 */
	@RequestMapping("/toDebitCard")
	public ModelAndView toDebitCard(HttpSession session) {
		ModelAndView mav = new ModelAndView();
		List<Map<String, Object>>  list = getDebitCardById(session);
		mav.addObject("cardList", list);
		mav.setViewName("debitCard");
		return mav;
	}
	/**
	 * 保存银行卡信息
	 * @param session
	 * @return
	 */
	@RequestMapping("/createDebitCard")
	public Map<String,Object> createDebitCard(HttpServletRequest request,HttpSession  session) {
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,Object> param = RequestUtil.convertParamToMap(request);
		//从session中取主键
		int userId = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
		
		param.put("userId", userId);
		//创建银行卡信息
		int num = userService.createDebitCard(param);
		if(num==1){
			map.put("success", true);
		}else{
			map.put("success", false);
		}
		return map;
	}
	/**
	 * 展示用户中心
	 * @param session
	 * @return
	 */
	public ModelAndView showUserCenter(HttpSession session){
		ModelAndView mav = new ModelAndView();
		
		//获取用户信息
		Map<String,Object> userinfo = this.getUserInfoBySession(session);
		
		String status = userinfo.get("status").toString();
		switch(status){
			//状态码为0,则状态为正常
			case "0":userinfo.put("status", Constants.USER_STATUS_0); break;
			case "1":userinfo.put("status", Constants.USER_STATUS_1); break;
		}
		
		mav.addObject("user",userinfo);
		return mav;
	}
	//TODO lsh修改
	/**
	 * 根据用户ID查询用户信息
	 * @param userId
	 * @return
	 */
	@RequestMapping("/getById")
	public Map<String,Object> getById(int userId){
		List<Map<String,Object>> userList = userService.getById(userId);
		Map<String,Object> userinfo = userList.get(0);
		return userinfo;
	}
	/**
	 * 用户登录验证
	 * @param user
	 * @return
	 */
	@RequestMapping("/login")
	public Map<String, Object> login(UserParam user, HttpSession session) {
		// 返回json
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		// 用户名密码不能为空
		if (user == null || user.getLoginname() == null
				|| user.getPassword() == null
				|| "".equals(user.getLoginname().trim())
				|| "".equals(user.getPassword().trim())) {
			//登录失败
			jsonMap.put("success", false);
			return jsonMap;
		}
		//###########################校验图片验证码
		//TODO

		// 传入参数
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("loginname", user.getLoginname().trim());
		param.put("password", MD5Util.md5(user.getPassword().trim()));
		List<Map<String,Object>> userList = userService.login(param);
		if (userList.size() == 1) {
			//##################################放入session
			session.setAttribute(Constants.USER_ID, userList.get(0).get("id"));
			//登录成功
			jsonMap.put("success", true);
			return jsonMap;
		} else {
			//登录失败
			jsonMap.put("success", false);
			return jsonMap;
		}
	}

	/**
	 * 用于校验 手机号码,邮箱,用户名是否已经被注册
	 * 
	 * @param type
	 *            类型: mobile/email/username
	 * @param value
	 *            值
	 * @return true:未被注册可以使用; false:被占用
	 */
	@RequestMapping("/isNotDuplication")
	public Map<String, Object> isNotDuplication(String type, String value) {
		// 返回json
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		//类型或者需要校验的类型不匹配mobile/email/username,则返回不可用
		if(type==null||value==null||"".equals(type.trim())||"".equals(value.trim())
			||(!"mobile".equals(type.trim())&&!"email".equals(type.trim())&&!"username".equals(type.trim()))	){
			//不可用
			jsonMap.put("success", false);
			return jsonMap;
		}
		
		// 传入参数,校验
		boolean isviable  = judgeNotDuplication(type,value);
		if (isviable) {
			//可用
			jsonMap.put("success", true);
			return jsonMap;
		} else {
			//不可用
			jsonMap.put("success", false);
			return jsonMap;
		}

	}

	
	/**
	 * 判断是否重复
	 * @param type
	 * @param value
	 * @return true:数据库中不存在/可用  false:数据库中存在/不可用
	 */
	public boolean judgeNotDuplication(String type, String value){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put(type.trim(), value.trim());
		int num = userService.isDuplication(param);
		if (num == 0) {
			//可用
			return true;
		} else {
			//不可用
			return false;
		}
	}
	
	/**
	 * 用户注册
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("/regist")
	public Map<String, Object> regist(User user) {
		// 返回json
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		// 手机号密码不能为空,手机号不能重复
		if (user == null || user.getMobile() == null
				|| user.getPassword() == null
				|| "".equals(user.getMobile().trim())
				|| "".equals(user.getPassword().trim())||!judgeNotDuplication("mobile",user.getMobile().trim()))   {
			// 登录失败
			jsonMap.put("success", false);
			return jsonMap;
		}

		// 传入参数
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("mobile", user.getMobile().trim());
		param.put("password", MD5Util.md5(user.getPassword().trim()));
		param.put("parentId", user.getParentId());
		int num = userService.createUser(param);
		if (num == 1) {
			jsonMap.put("success", true);
			return jsonMap;
		} else {
			jsonMap.put("success", false);
			return jsonMap;
		}
	}
	
	/**
	 * 退出
	 */
	@RequestMapping("/logout")
	public void logout(HttpSession session) {
		
		//移除session中的用户ID
		session.removeAttribute(Constants.USER_ID);
	}
	


	
	/**
	 * 更改用户中心信息
	 */
	@RequestMapping("/saveuserinfo")
	public Map<String, Object> saveUserInfo(HttpServletRequest request,HttpSession session) {
		//TODO 用户名 必须含有字母,并且不能出现@
		// 返回json
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Map<String,Object> userInfo = RequestUtil.convertParamToMap(request);
		  int num = update(userInfo, session);
		
		if (num == 1) {
			jsonMap.put("success", true);
			return jsonMap;
		} else {
			jsonMap.put("success", false);
			return jsonMap;
		}
	}
	@RequestMapping("/modifypassword")
	public Map<String, Object> modifyPassword(String password,String newpassword,HttpSession session){
		// 返回json
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Map<String,Object> userInfo = new HashMap<String,Object>();
		
		//TODO 判断密码是否正确
		
		//更新密码		采用md5加密
		userInfo.put("password",  MD5Util.md5(newpassword.trim()));
		 int num = update(userInfo, session);
			
			if (num == 1) {
				jsonMap.put("success", true);
				
			} else {
				jsonMap.put("success", false);
			}
			return jsonMap;
	}
	
	
	@RequestMapping("/modifyPayPassword")
	public Map<String, Object> modifyPayPassword(String password,String payPassword,HttpSession session){
		// 返回json
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		Map<String,Object> userInfo = new HashMap<String,Object>();
		
		//TODO 判断密码是否正确
		
		//更新密码		采用md5加密
		userInfo.put("payPassword",  MD5Util.md5(payPassword.trim()));
		 int num = update(userInfo, session);
			
			if (num == 1) {
				jsonMap.put("success", true);
				
			} else {
				jsonMap.put("success", false);
			}
			return jsonMap;
	}
	
	
	
	/**
	 * 用户信息更改
	 */
	@RequestMapping("/update")
	public int update(Map<String,Object> userInfo, HttpSession session) {
		//TODO 用户名 必须含有字母,并且不能出现@
		String id = session.getAttribute(Constants.USER_ID).toString();
		
		//Map<String, Object> param = new HashMap<String, Object>();
		userInfo.put("id", id);
		
		
		int res = userService.updateUser(userInfo);
		return res;
	}
	
	/**
	 * 根据session获取用户信息
	 * @param session
	 * @return
	 */
	public Map<String,Object> getUserInfoBySession(HttpSession session){
		int id = getUserIdBySession(session);
		
		List<Map<String,Object>> userList = userService.getById(id);
		Map<String,Object> userinfo = userList.get(0);
		return userinfo;
	}
	
	
	/**
	 * 根据session获取用户主键
	 * @param session
	 * @return
	 */
	public Integer getUserIdBySession(HttpSession session){
		return Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
	}
	
	
	/**
	 * 根据session判断该用户是不是队长  true:是队长, false:不是队长
	 * @param session
	 * @return
	 */
	public boolean isCaptainBySession(HttpSession session){
		return Constants.USER_IS_CAPTAIN.equals(getUserInfoBySession(session).get("isCaptain").toString());
	}
	
	
	
	/**
	 * 删除银行卡 逻辑删除
	 * @param ids
	 * @return
	 */
	@RequestMapping("/deleteDebitCard")
	@ResponseBody
	public Map<String, Object> deleteDebitCard(int[] ids) {
		// 返回json
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if(ids.length>0){
		for (int id : ids) {

			// 传入参数
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("id", id);
			param.put("isDelete", 1); // 0表示正在使用, 1表示删除

			int num = updateDebitCardById(param);
			if (num <= 0) {

				jsonMap.put("success", false);
				return jsonMap;
			}
		}
		jsonMap.put("success", true);
		
		}else{
			//没有勾选条目则删除失败
			jsonMap.put("success", false);
		}
		
		return jsonMap;
	}
	
	
	
	/**
	 * 根据用户逐渐爱你查询银行卡信息
	 * @param session
	 * @return
	 */
	public List<Map<String,Object>> getDebitCardById(HttpSession session){
		//从session中取主键
		int id = Integer.parseInt(session.getAttribute(Constants.USER_ID).toString());
		
		List<Map<String,Object>> debitCardList = userService.getDebitCardById(id);
		
		
		return debitCardList;
	}
	
	
	
	/**
	 * 更新银行卡信息
	 * @param param
	 * @return
	 */
	public int updateDebitCardById(Map<String,Object> param){
	
		int num = userService.updateDebitCard(param);
		
		return num;
	}
	
	
	/**
	 * 上传头像
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/upload",method=RequestMethod.POST)
	public Map<String, Object> upload(HttpServletRequest req) {
		MultipartResolver resolver = new CommonsMultipartResolver(req.getSession().getServletContext());
		MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(req);
		Map<String, Object> result = new HashMap<String, Object>();
		String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
		String suffix = FileUtil.upload("doc", Constants.FILE_ROOT + Constants.PRODUCT_FILE_DIR + fileName, multipartRequest);
		result.put("fileName", suffix.equals("") ? "" : fileName + suffix);
		return result;
	}
}
